package com.yuan.aicodemother.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.yuan.aicodemother.exception.BusinessException;
import com.yuan.aicodemother.exception.ErrorCode;
import com.yuan.aicodemother.mapper.UserMapper;
import com.yuan.aicodemother.model.dto.user.UserAddRequest;
import com.yuan.aicodemother.model.entity.User;
import com.yuan.aicodemother.model.vo.LoginUserVO;
import com.yuan.aicodemother.model.vo.UserVO;
import com.yuan.aicodemother.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.yuan.aicodemother.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户 服务层实现。
 *
 * @author XueYuan
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验参数
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        QueryWrapper userQuery = new QueryWrapper();
        userQuery.eq("userAccount", userAccount);
        userQuery.eq("userPassword", userPassword);
        User user = userMapper.selectOneByQuery(userQuery);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名或密码错误");
        }
        //用户脱敏
        LoginUserVO loginUserVO = this.getLoginUserVO(user);
        //保存用户信息
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return loginUserVO;
    }

    @Override
    public Boolean addUser(UserAddRequest userAddRequest) {
        //校验账号和密码是否为空
        if (StrUtil.hasBlank(userAddRequest.getUserAccount(), userAddRequest.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码为空");
        }
        //校验当前用户是否存在
        String userAccount = userAddRequest.getUserAccount();
        QueryWrapper userQuery = new QueryWrapper();
        userQuery.eq("userAccount", userAccount);
        User user = userMapper.selectOneByQuery(userQuery);
        if (user != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"该用户已存在");
        }
        //添加用户
        boolean saveResult = this.save(user);
        if (!saveResult){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户数据保存失败");
        }
        return saveResult;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }
}
